import { genChartByAiUsingPost } from '@/services/ZNBI/chartController';
import { UploadOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  Flex,
  Form,
  Input,
  message,
  Row,
  Select,
  Upload,
  UploadProps,
} from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useState } from 'react';

const { TextArea } = Input;

const AddChart: React.FC = () => {
  const [chart, setChart] = useState<API.AiResponseVO>();
  const [submitting, setSubmitting] = useState<boolean>();
  const [form] = Form.useForm(); // 获取表单实例
  const [options, setOptions] = useState<any>();

  const props: UploadProps = {
    name: 'file',
    action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  /**
   * 提交表单
   * @param values
   */
  const onFinish = async (values: any) => {
    //防止重复提交
    if (submitting) {
      return;
    }
    setSubmitting(true);

    //对接后端上传数据
    const params = {
      ...values,
      file: undefined,
    };

    try {
      const res = await genChartByAiUsingPost(params, {}, values.file.file.originFileObj);
      if (!res?.data) {
        message.error('分析失败0');
      } else {
        message.success('分析成功');
        console.log(res.data.code);
        console.log(666);
        const chartOption = JSON.parse(res.data.code);
        console.log(777);
        console.log(chartOption);

        if (!chartOption) {
          throw new Error('图表代码解析错误');
        } else {
          console.log(888);
          setChart(res.data);
          setOptions(chartOption);
        }
      }
    } catch (e) {
      message.error('分析失败1', e.message);
    }

    setSubmitting(false);
  };

  const onReset = () => {
    form.resetFields(); // 重置表单
  };
  /*const option= {
  title: { text: '用户数量增长趋势' },
  tooltip: {},
  xAxis: { type: 'category', data: ['2022', '2023', '2024'] },
  yAxis: { name: '用户数量' },
  series: [{
    type: 'line',
    data: [1001, 500, 3000],
    markPoint: { data: [{ coord: ['2024', 3000] }] }
  }]
}*/
  return (
    <div className="add-chart">
      <Row>
        <Col span={12}>
          <Card title="分析目标">
            <Form form={form} name="addChart" onFinish={onFinish} initialValues={{}}>
              <Form.Item label="图表类型" name="chartType">
                <Select
                  options={[
                    { value: '折线图', label: '折线图' },
                    { value: '柱状图', label: '柱状图' },
                    { value: '堆叠图', label: '堆叠图' },
                    { value: '饼图', label: '饼图' },
                    { value: '雷达图', label: '雷达图' },
                  ]}
                />
              </Form.Item>

              <Form.Item
                label="分析目标"
                name="goal"
                rules={[{ required: true, message: '请输入分析目标' }]}
              >
                <TextArea rows={4} placeholder="请输入你的分析需求，比如分析网站用户的增长情况" />
              </Form.Item>

              <Form.Item
                label="图表名称"
                name="name"
                rules={[{ required: true, message: '请输入图表名称' }]}
              >
                <Input placeholder="请输入图表名称" />
              </Form.Item>

              <Form.Item label="上传文件" name="file">
                <Upload {...props}>
                  <Button icon={<UploadOutlined />}>上传CSV文件</Button>
                </Upload>
              </Form.Item>

              <Flex gap="small" wrap>
                <Button type="primary" htmlType="submit" loading={submitting} disabled={submitting}>
                  智能分析
                </Button>
                <Button type="default" onClick={onReset}>
                  重置
                </Button>
              </Flex>
            </Form>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="分析结论">{chart?.aiResponse}</Card>
          <Card title="生成图表">{options && <ReactECharts option={options} />}</Card>
        </Col>
      </Row>
    </div>
  );
};

export default () => <AddChart />;
